/*
 * Copyright (C) 2014 The Senzu Dev Team
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package gui;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.sql.SQLException;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
import static jr.Reporter.LiquidacionParticularReport;
import logic.LiquidacionParticular;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.view.JasperViewer;
import util.InputHelper;

/**
 *
 * @author lucifer
 */
public class LiquidacionParticularDialog extends javax.swing.JDialog {

  public static final int RET_CANCEL = 0;
  public static final int RET_OK = 1;

  private LocalDate lastMonday;

  public LiquidacionParticularDialog(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
    initCal();

    ManoSanta();
    selectLastMonday();

    String cancelName = "cancel";
    InputMap inputMap = getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), cancelName);
    ActionMap actionMap = getRootPane().getActionMap();
    actionMap.put(cancelName, new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        doClose(RET_CANCEL);
      }
    });
  }

  public int getReturnStatus() {
    return returnStatus;
  }

  private void initCal() {
    jCalendar1.getDayChooser().setDayBordersVisible(false);
    jCalendar1.getDayChooser().setDecorationBackgroundVisible(false);
    jCalendar1.getDayChooser().setDecorationBordersVisible(false);
    jCalendar1.setDecorationBackgroundVisible(false);
    jCalendar1.setDecorationBordersVisible(false);
    jCalendar1.getMonthChooser().SetLiquidacionParticularDialog(this); // dirty hack
  }

  public void ManoSanta() {
    JButton[] days = jCalendar1.getDayChooser().GetJButtons();
    jCalendar1.getDayChooser().DisableAllDayButtons();

    LocalDate tomorrow = LocalDate.now().plusDays(1);
    LocalDate date;
    int year, month, day;

    for (int i = 7; i < days.length; i++) {
      try {
        day = Integer.parseInt(days[i].getText());
        month = jCalendar1.getMonthChooser().getMonth() + 1;
        year = jCalendar1.getYearChooser().getYear();
        date = LocalDate.of(year, month, day);
        if (date.getDayOfWeek().equals(DayOfWeek.MONDAY) && date.isBefore(tomorrow)) {
          days[i].setEnabled(true);
        }
      } catch (Exception e) {
      }
    }
  }

  private void selectLastMonday() {
    lastMonday = LocalDate.now();
    while (!lastMonday.getDayOfWeek().equals(DayOfWeek.MONDAY)) {
      lastMonday = lastMonday.plusDays(-1);
    }

    jCalendar1.setDate(InputHelper.FromNewDateToOld(lastMonday.atStartOfDay()));

    jLabel1.setText(
      String.format("<html><b>Semana del lunes %s</b></html>", lastMonday.format(DateTimeFormatter.ofPattern("dd/MM/yy")))
    );
  }

  public void SelectedDay() {
    if (lastMonday == null) {
      return;
    }

    LocalDate monday = InputHelper.FromOldDateToNew(jCalendar1.getDate()).toLocalDate();

    while (!monday.getDayOfWeek().equals(DayOfWeek.MONDAY)) {
      monday = monday.plusDays(-1);
    }

    jLabel1.setText(
      String.format("<html><b>Semana del lunes %s</b></html>",
        monday.isAfter(lastMonday) ? lastMonday.format(DateTimeFormatter.ofPattern("dd/MM/yy")) : monday.format(DateTimeFormatter.ofPattern("dd/MM/yy"))
      )
    );
  }

  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    okButton = new javax.swing.JButton();
    cancelButton = new javax.swing.JButton();
    jLabel1 = new javax.swing.JLabel();
    jCalendar1 = new kalendar.calendar.JCalendar();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("Liquidación de Pacientes Particulares");
    setResizable(false);
    addWindowListener(new java.awt.event.WindowAdapter() {
      public void windowClosing(java.awt.event.WindowEvent evt) {
        closeDialog(evt);
      }
    });

    okButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/aceptar.png"))); // NOI18N
    okButton.setText("Aceptar");
    okButton.setMaximumSize(new java.awt.Dimension(120, 27));
    okButton.setMinimumSize(new java.awt.Dimension(120, 27));
    okButton.setPreferredSize(new java.awt.Dimension(120, 27));
    okButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        okButtonActionPerformed(evt);
      }
    });

    cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/cancelar.png"))); // NOI18N
    cancelButton.setText("Cancelar");
    cancelButton.setMaximumSize(new java.awt.Dimension(120, 27));
    cancelButton.setMinimumSize(new java.awt.Dimension(120, 27));
    cancelButton.setPreferredSize(new java.awt.Dimension(120, 27));
    cancelButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        cancelButtonActionPerformed(evt);
      }
    });

    jLabel1.setText("Liquidación de la semana");
    jLabel1.setToolTipText("Seleccione el lunes de la semana deseada.");

    jCalendar1.setToolTipText("Seleccione el lunes de la semana deseada.");
    jCalendar1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
      public void propertyChange(java.beans.PropertyChangeEvent evt) {
        jCalendar1PropertyChange(evt);
      }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
        .addGap(12, 12, 12)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jLabel1)
          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
            .addGroup(layout.createSequentialGroup()
              .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
              .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addComponent(jCalendar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        .addGap(12, 12, 12))
    );

    layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cancelButton, okButton});

    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
        .addGap(12, 12, 12)
        .addComponent(jLabel1)
        .addGap(18, 18, 18)
        .addComponent(jCalendar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addGap(18, 18, 18)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addContainerGap())
    );

    getRootPane().setDefaultButton(okButton);

    pack();
  }// </editor-fold>//GEN-END:initComponents

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
      doClose(RET_OK);

      LocalDate monday = InputHelper.FromOldDateToNew(jCalendar1.getDate()).toLocalDate();

      while (!monday.getDayOfWeek().equals(DayOfWeek.MONDAY)) {
        monday = monday.plusDays(-1);
      }

      if (monday.isAfter(lastMonday)) {
        monday = lastMonday;
      }

      try {
        LiquidacionParticular liquidacionParticular = new LiquidacionParticular(monday);
        JasperPrint jp = LiquidacionParticularReport(liquidacionParticular.GenerarLiquidacion());

        JasperViewer viewer = new JasperViewer(jp, false);
        viewer.setTitle(
          String.format("Liquidación de Particulares de la Semana del Lunes %s", monday.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")))
        );
        viewer.setVisible(true);
        viewer.setFitWidthZoomRatio();

      } catch (SQLException e) {
        System.out.printf("?db liquidación particular issue\n");
      } catch (JRException e) {
        System.out.printf("?print liquidación particular issue\n");
      }
    }//GEN-LAST:event_okButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
      doClose(RET_CANCEL);
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog
      doClose(RET_CANCEL);
    }//GEN-LAST:event_closeDialog

  private void jCalendar1PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jCalendar1PropertyChange
    ManoSanta();
    SelectedDay();
  }//GEN-LAST:event_jCalendar1PropertyChange
  
  private void doClose(int retStatus) {
    returnStatus = retStatus;
    setVisible(false);
    dispose();
  }

  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton cancelButton;
  private kalendar.calendar.JCalendar jCalendar1;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JButton okButton;
  // End of variables declaration//GEN-END:variables

  private int returnStatus = RET_CANCEL;
}
